package io.renren.modules.oss.cos.service.impl;

import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.UploadResult;
import com.qcloud.cos.transfer.TransferManager;
import com.qcloud.cos.transfer.Upload;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.Result;
import io.renren.modules.oss.cos.service.OssOperateService;
import io.renren.modules.security.user.UserDetail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import io.renren.modules.oss.cos.dto.FileUploadReq;

import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * @author yun lang
 * @version 1.0
 * @description: OSS服务实现
 * @date 2024/11/6 09:30
 */
@Service
public class OssOperateServiceImpl implements OssOperateService {
    private static final Logger logger = LoggerFactory.getLogger(OssOperateServiceImpl.class);

    private static final Set<String> VIDEO_EXTENSIONS = new HashSet<>(Arrays.asList(
            "mp4", "m4p", "m4a", "3g2", "mkv", "webm", "flv", "vob", "ogv", "ogg", "drc", "gifv", "mng", "asf", "wmv", "avi", "mov", "qt", "amv", "mpg", "mpeg", "mpe", "mpv", "m2v", "m4v", "svi", "3gp", "3g2", "f4v", "f4p", "f4a", "f4b"
    ));

    @Value("${tencent.cos.region}")
    private String region;

    @Value("${tencent.cos.bucketName}")
    private String bucketName;

    @Autowired
    private TransferManager transferManager;

    @Override
    public Result uploadFile(FileUploadReq fileUploadReq, UserDetail user) {
        MultipartFile multipartFile = fileUploadReq.getFile();


        String time = DateUtils.dateTimeNow();
        String dateStr = time.substring(0, 8);
        String endStr = time.substring(8);
        String key = dateStr + "/" + user.getId() + endStr + "." + getFileExtension(multipartFile);
        // 指定要上传的文件
        PutObjectRequest putObjectRequest = null;
        try {
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(multipartFile.getSize());

            putObjectRequest = new PutObjectRequest(bucketName, key, multipartFile.getInputStream(), objectMetadata);

            Upload upload = transferManager.upload(putObjectRequest);
            UploadResult uploadResult = upload.waitForUploadResult();
            uploadResult.getRequestId();
            // 返回上传后的文件 URL
            String url = "https://" + bucketName + ".cos." + region + ".myqcloud.com/" + key;

            // 存储


        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return null;
    }


    @Override
    public boolean isVideoByExtension(MultipartFile file) {
        if (file == null || file.getOriginalFilename() == null) {
            return false;
        }

        String originalFilename = file.getOriginalFilename();
        int lastIndexOfDot = originalFilename.lastIndexOf('.');
        if (lastIndexOfDot == -1) {
            // 没有后缀名
            return false;
        }

        String fileExtension = originalFilename.substring(lastIndexOfDot + 1).toLowerCase();
        return VIDEO_EXTENSIONS.contains(fileExtension);
    }

    private String getFileExtension(MultipartFile file) {
        if (file == null || file.getOriginalFilename() == null) {
            return null;
        }

        String originalFilename = file.getOriginalFilename();
        int lastIndexOfDot = originalFilename.lastIndexOf('.');
        if (lastIndexOfDot == -1) {
            // 没有后缀名
            return "";
        }

        return originalFilename.substring(lastIndexOfDot + 1).toLowerCase();
    }
}
